﻿using DefCore.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DefCore.Mapping
{
    public static class CellFactory
    {
        public static T Create<T>(DungeonPos pos)
            where T : CellBase
        {
            return Create<T>(pos, null);
        }
        
        public static T Create<T>(DungeonPos pos, KeyValuePair<string, object>[] setters)
            where T : CellBase
        {
            ConstructorInfo cinfo = typeof(T).GetConstructor(new Type[] { typeof(DungeonPos) });

            if (cinfo == null)
                throw new Exception(string.Format("No Valid Constructor found for type '{0}'", typeof(T).ToString()));

            T obj = (T)cinfo.Invoke(new object[] {pos});

            if (setters == null)
                return obj;

            foreach (KeyValuePair<string, object> pair in setters)
            {
                PropertyInfo pinfo = typeof(T).GetProperty(pair.Key);

                if (pinfo == null)
                    continue;

                pinfo.SetValue(obj, pair.Value, null);
            }

            return obj;
        }
    }
}
